import {useEffect, useState} from 'react';
import {hostAddr} from '@/config.js';

export function useLanguageUseAnalysisStream(messageId) {
  const [messages, setMessages] = useState([]);
  const [error, setError] = useState(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    if (!messageId) return;

    const url = `${hostAddr}/language-use/analysis/${messageId}/stream`;
    const eventSource = new EventSource(url);

    eventSource.onmessage = (event) => {
      setMessages((prev) => [...prev, event.data]);
    };

    eventSource.onopen = () => {
      setConnected(true);
    };

    eventSource.onerror = (err) => {
      setError(err);
      eventSource.close();
    };

    return () => {
      eventSource.close();
    };
  }, [messageId]);

  return {messages, error, connected};
}